<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>WS Interview Test</title></head>
<body>
  <h3>实时面试测试</h3>
  <button id="startBtn">开始</button>
  <pre id="log"></pre>
  <script>
    const logEl = document.getElementById('log');
    function log(msg){ logEl.textContent += msg + '\\n'; }

    let ws, recorder, audioCtx, processor;
    document.getElementById('startBtn').onclick = async () => {
      ws = new WebSocket('ws://localhost:8000/ws/interview/1/');
      ws.onopen = () => log('WS 已连接');
      ws.onmessage = e => {
        const msg = JSON.parse(e.data);
        log('[WS 收到] ' + JSON.stringify(msg));
      };

      // 获取麦克风
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      audioCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate:16000 });
      const source = audioCtx.createMediaStreamSource(stream);
      processor = audioCtx.createScriptProcessor(4096, 1, 1);
      source.connect(processor); processor.connect(audioCtx.destination);

      processor.onaudioprocess = e => {
        const input = e.inputBuffer.getChannelData(0);
        // 转 Int16
        const pcm = new Int16Array(input.length);
        for(let i=0;i<input.length;i++){
          let s = Math.max(-1, Math.min(1, input[i]));
          pcm[i] = s<0 ? s*0x8000 : s*0x7FFF;
        }
        // 发送二进制
        ws.send(pcm.buffer);
      };

      // 通知后端开始
      ws.send(JSON.stringify({ type:'start_answer' }));
    };
  </script>
</body>
</html>
